package peer.model.transfer.block;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import peer.model.consts.TransferConsts;

public class BlockTransfer {

	public static byte[] readBlock(InputStream from, int skipBytes, int bytesToRead) throws IOException{
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		byte[] buffer = new byte[bytesToRead];
		int bytesRead;
		from.skip(skipBytes);
		if ((bytesRead = from.read(buffer)) > 0){
		out.write(buffer, 0, bytesRead);
		}
		return out.toByteArray();
	}

	public static void copyBlock(int offset, InputStream blockSource, OutputStream out) throws IOException{
		for(int a=0;a<TransferConsts.BLOCK_SIZE/TransferConsts.TRANSFER_BUFFER_SIZE;a++){
			out.write(BlockTransfer.readBlock(blockSource, offset + (a*TransferConsts.TRANSFER_BUFFER_SIZE), TransferConsts.TRANSFER_BUFFER_SIZE));
			out.flush();
		}
	}

	public static void main(String args[]){
		FileInputStream fileIn1 = null;
		FileInputStream fileIn2 = null;
		FileOutputStream fileOut = null;
		try {
			fileIn1 = new FileInputStream("C:/example.mp3");
			fileIn2 = new FileInputStream("C:/example.mp3");

			fileOut=new FileOutputStream("C:/salida.mp3");
			for(int a=0;a<10;a++){
				copyBlock(a*TransferConsts.BLOCK_SIZE, fileIn1, fileOut);
				Thread.sleep(5000);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally{
			try {
				fileIn1.close();
				fileIn2.close();
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
